Using sysconf in Ruby with FFI

2012-10-15

Just a quick snippet that makes it easier to use getconf by using the sysconf function.

require 'ffi'

module Sysconf
  extend FFI::Library
  ffi_lib ["c"]

  SYSCONF_ARGS = [
    :_SC_ARG_MAX,
    :_SC_CHILD_MAX,
    :_SC_CPU_TIME,
    :_SC_THREAD_CPU_TIME,
  ]

  enum SYSCONF_ARGS
  attach_function :sysconf, [:int], :long

  class << self
    SYSCONF_ARGS.each do |e|
      method_name = e.to_s.sub(/^_SC_/, '').downcase
      define_method(method_name){ sysconf(e) }
    end
  end
end

p arg_max: Sysconf.arg_max
p cpu_time: Sysconf.cpu_time
p thread_cpu_time: Sysconf.thread_cpu_time